import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { tag } from '../../entities/tag.entity';
import { TagDelete, TagDto } from './dto/tag.dto';
import * as dayjs from 'dayjs';
import { v4 as uuidv4 } from 'uuid';
import { API } from '../../types';

@Injectable()
export class TagService {
  constructor(
    @InjectRepository(tag)
    private readonly tag: Repository<tag>,
  ) {}

  async create(data: TagDto) {
    const { name, intro, id } = data;
    if (id) {
      await this.tag.update(
        { id },
        { name, intro, updateTime: dayjs().unix() },
      );
      return { message: '修改成功' };
    }
    await this.tag.insert({
      id: uuidv4(),
      name,
      intro,
      creationTime: dayjs().unix(),
      updateTime: dayjs().unix(),
    });
    return { message: '添加成功' };
  }
  async list(query: API.paging, req: any) {
    // console.log(req);
    req;
    const { current = 1, pageSize = 15 } = query;
    const [users, total] = await this.tag.findAndCount({
      skip: (current - 1) * pageSize,
      take: pageSize,
      order: {
        updateTime: 'DESC',
      },
    });
    return { list: users, total };
  }

  async findAll(query: API.paging) {
    return await this.tag.find();
  }

  async info(query: TagDelete) {
    const { id } = query;
    const res = await this.tag.findOne({
      where: { id },
    });
    return res;
  }
  async delete(query: TagDelete) {
    await this.tag.delete({ id: query.id });
    return { message: '删除成功' };
  }
}
